import VConsole from 'vconsole';
import * as config from '../config/config';

const getQueryString = () => {
    const qs = (location.search.length > 0 ? location.search.substring(1) : '');
    const items = qs.length ? qs.split('&') : [];
    const args = {};

    for (let i = 0; i < items.length; i++) {
        const item = items[i].split('=');
        const name = decodeURIComponent(item[0]);
        const value = decodeURIComponent(item[1]);
        if (name.length) {
            args[name] = value;
        }
    }

    return args;
};

const getUserInfoFromQiuBaiApp = () => {
    return new Promise((resolve, reject) => {
        if (config.IS_DEV_ENV) {
            resolve({
                Qbtoken: 'bc6b9110a7274709c7d18b6aae836a7b0394ea80'
            });
            return;
        }

        // native回调函数入口
        window.Interface = {
            onNativeResp: function (callbackName, params) {
                const res = (JSON.parse(params) || {}).content || {};
                try {
                    res.Qbtoken = res.token;
                    resolve(res);
                }
                catch (err) {
                    reject(res.err_msg);
                }
            }
        };

        prompt('__native_call=>' + JSON.stringify({
            method: 'reqNative',
            modul: 'account',
            action: 'getInfo',
            args: {
            },
            callbackId: 'requestNativeUserInfoCallback'
        }));
    });
};

const addVConsole = () => {
    const vConsole = new VConsole();
    vConsole.setOption({
        onReady: () => {
            vConsole.hideSwitch();
        }
    });

    let pageClickStartTime = 0;
    let pageClickTime = 0;
    const handlePageClick = () => {
        const now = Date.now();

        if (pageClickStartTime === 0 && pageClickTime === 0) {
            pageClickStartTime = now;
        }

        if ((now - pageClickStartTime) < 1000) {
            ++pageClickTime;

            if (pageClickTime >= 8) {
                vConsole.showSwitch();
                pageClickStartTime = 0;
                pageClickTime = 0;
            }
        }

        if ((now - pageClickStartTime) >= 2000) {
            pageClickStartTime = 0;
            pageClickTime = 0;
        }
    };

    document.body.ontouchstart = () => {
        handlePageClick();
    };
};

const deleteArrayItem = (array, func) => {
    const deleteIndex = array.findIndex((item, index) => {
        return func(item, index, array);
    });

    return array.splice(deleteIndex, 1);
};

const addArrayItem = (array, item) => {
    array.push(item);
    return array;
};

const navigate = (url, isWeb = false, needNavBar = true) => {
    let jumpUrl = '';
    if (isWeb) {
        if (needNavBar) {
            jumpUrl = `mqsbk://web/${url}`;
        }
        else {
            jumpUrl = `mqsbk://immersion_web/${url}`;
        }
    }
    else {
        jumpUrl = url;
    }

    prompt('__native_call=>' + JSON.stringify({
        method: 'reqNative',
        action: 'deeplink',
        modul: 'jump',
        callbackId: 'callback',
        args: {
            url: jumpUrl
        }
    }));
};

navigate.back = () => {
    prompt('__native_call=>' + JSON.stringify({
        method: 'reqNative',
        action: 'deeplink',
        modul: 'jump',
        callbackId: 'callback',
        args: {
            url: 'mqsbk://main'
        }
    }));
};

const disableDocumentScroll = {
    add: () => {
        const head = document.head || document.getElementsByTagName('head')[0];
        const html = document.documentElement || document.getElementsByTagName('html')[0];
        const body = document.body || document.getElementsByTagName('body')[0];
        const cssRules = `
            .disableDocumentScroll {
                position: relative;
                box-sizing: border-box;
                width: 100%;
                height: 100%;
                overflow: hidden;
            }
        `;
        const style = document.createElement('style');
        style.id = 'disableDocumentScroll';
        style.type = 'text/css';

        if (style.styleSheet) {
            style.styleSheet.cssText = cssRules;
        }
        else {
            style.appendChild(document.createTextNode(cssRules));
        }

        head.appendChild(style);
        html.classList.add('disableDocumentScroll');
        body.classList.add('disableDocumentScroll');
    },
    remove: () => {
        const html = document.documentElement || document.getElementsByTagName('html')[0];
        const body = document.body || document.getElementsByTagName('body')[0];
        const head = document.head || document.getElementsByTagName('head')[0];
        const style = document.getElementById('disableDocumentScroll');
        if (style) {
            if (style.remove) {
                style.remove();
            }
            else {
                head.removeChild(style);
            }
        }

        html.classList.remove('disableDocumentScroll');
        body.classList.remove('disableDocumentScroll');
    }
};

const isIos = () => {
    const ua = navigator.userAgent.toLowerCase();

    if (ua.match('android')) {
        return false;
    }
    else if (ua.match('iphone')) {
        return true;
    }
    else if (ua.match('ipod')) {
        return true;
    }
    else if (ua.match('ipad')) {
        return true;
    }
    else {
        return false;
    }
};

const isIPhoneX = () => {
    return isIos() && (screen.height === 812 && screen.width === 375);
};

export {
    getQueryString,
    getUserInfoFromQiuBaiApp,
    addVConsole,
    addArrayItem,
    deleteArrayItem,
    navigate,
    disableDocumentScroll,
    isIos,
    isIPhoneX
};
